package com.ss.web.tagmark.service;

import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.jpa.repository.JpaRepository;

import com.ss.web.tagmark.dao.BaseRepository;

/**
 *
 * @author taofucheng
 *
 * @param <T>
 *            要操作的实体对象
 */
public abstract class BaseService<T> {
	protected Logger logger = LoggerFactory.getLogger("sys");
	@Autowired
	private JpaRepository<T, Long> repo;
	@PersistenceContext
	protected EntityManager entityManager;

	/**
	 * 查询分页信息
	 * 
	 * @param parameterMap
	 *            一些分页条件
	 * @param entity
	 *            详细的查询信息
	 * @return
	 */
	public Page<T> getListByPage(Map<String, String[]> parameterMap, T entity) {
		if (!(repo instanceof BaseRepository)) {
			System.err.println("DAO对象需要实现或继承自BaseRepository");
			return null;// 不是对应的实体
		}
		int page = getIntParameter(parameterMap, "page", 0);
		int size = getIntParameter(parameterMap, "size", 20);
		String orderby = getParameter(parameterMap, "order", "");
		try {
			Pageable paging = null;
			if (StringUtils.isBlank(orderby)) {
				paging = PageRequest.of(page, size);
			} else {
				// 解析order
				orderby = orderby.replaceAll("\\s+", " ");// 把多个空格合并成一个空格
				String[] parts = orderby.split(" ");
				if (parts.length <= 2) {// 不是field asc这样的结构
					String field = parts[0];
					String o = parts.length == 2 ? parts[1].toLowerCase() : "asc";
					paging = PageRequest.of(page, size,
							Sort.by(o.equals("asc") ? Order.asc(field) : Order.desc(field)));
				}
			}
			if (paging == null) {
				paging = PageRequest.of(page, size);
			}
			return ((BaseRepository<T, Long>) repo).findByPage(entity, paging, entityManager);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	protected int getIntParameter(Map<String, String[]> parameterMap, String key, int defaultValue) {
		String ret = getParameter(parameterMap, key, "");
		if (StringUtils.isNumeric(ret)) {
			return Integer.parseInt(ret);
		} else {
			return defaultValue;
		}
	}

	private String getParameter(Map<String, String[]> parameterMap, String key, String defaultValue) {
		String[] values = parameterMap.get(key);
		String ret = defaultValue;
		if (values != null && values.length > 0) {
			for (String v : values) {
				if (v != null && v.trim().length() > 0) {
					ret = v;
					break;
				}
			}
		}
		return ret;
	}
}
